package com.lagou.registry;

import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;

import java.util.List;

public class ZkNodeUtil {

    private static CuratorFramework client = ZkClientHolder.client;
    /**
     * 判断节点是否存在
     * @param path
     * @return
     */
    public static boolean isExistsNode(String path){
        client.sync();
        try {
            return client.checkExists().forPath(path) != null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 创建节点
     * @param mode
     * @param path
     */
    public static void createNode(CreateMode mode, String path){
        try {
            client.create().creatingParentsIfNeeded().withMode(mode).forPath(path);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新节点
     * @param path
     * @param nodeData
     */
    public static void setNodeData(String path,String nodeData){
        try {
            client.setData().forPath(path,nodeData.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建节点和数据
     * @param mode
     * @param path
     * @param nodeData
     */
    public static void createNodeAndData(CreateMode mode,String path,String nodeData){
        try {
            System.out.println("path:"+path+",nodeData:"+nodeData+",client:"+client);
            client.create().creatingParentsIfNeeded().withMode(mode).forPath(path,nodeData.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取节点数据
     * @param path
     * @return
     */
    public static String getNodeData(String path){
        try {
            byte[] bytes = client.getData().forPath(path);
            return new String(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取所有子节点
     * @param path
     * @return
     */
    public static List<String> getNodeChild(String path){
        try {
            List<String> list = client.getChildren().forPath(path);
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 是否递归删除节点，
     * @param path
     * @param recursive
     */
    public static void deleteNode(String path,Boolean recursive){
        try {
            if(recursive){
                client.delete().guaranteed().deletingChildrenIfNeeded().forPath(path);
            }else{
                client.delete().guaranteed().forPath(path);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}
